<template>
  <el-card class="global-card">
    <template #header>
      <div class="card-header">
        <span>会员列表</span>
      </div>
    </template>
    <AsideSearch
      :is-loading="loadOpts.refresh"
      @on-search="handleClickSearch"
    />
    <el-table
      :data="tableData"
      style="width: 100%; margin: 20px 0"
      border
      highlight-current-row
    >
      <!-- <el-table-column prop="id" label="#ID" min-width="56"></el-table-column> -->
      <el-table-column label="渠道商" min-width="256">
        <template #default="scope">
          <ProfilePanel
            :avatar="scope.row.avatar"
            :nickname="scope.row.nickname"
            :remark="scope.row.remark"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="unionId"
        label="小程序ID"
        min-width="224"
      ></el-table-column> -->
      <!-- <el-table-column
        prop="mobile"
        label="授权手机号"
        min-width="128"
      ></el-table-column> -->
      <el-table-column label="佣金（剩余佣金）" min-width="128">
        <template #default="scope">
          <PipeMoney type="1" :money="scope.row.bonus" />
        </template>
      </el-table-column>
      <el-table-column label="佣金（累计佣金）" min-width="128">
        <template #default="scope">
          <PipeMoney type="1" :money="scope.row.bonusTotal" />
        </template>
      </el-table-column>
      <el-table-column label="积分（剩余积分）" min-width="128">
        <template #default="scope">
          <PipeMoney type="2" :money="scope.row.credits" />
        </template>
      </el-table-column>
      <el-table-column label="积分（累计积分）" min-width="128">
        <template #default="scope">
          <PipeMoney type="2" :money="scope.row.creditsTotal" />
        </template>
      </el-table-column>
      <el-table-column label="直属上级" min-width="256">
        <template #default="scope">
          <ProfilePanel
            v-if="scope.row.parent"
            :avatar="scope.row.parent.avatar"
            :nickname="scope.row.parent.nickname"
            :remark="scope.row.parent.remark"
            isNav
          />
          <span v-else>--</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="uniqueCode"
        label="邀请码"
        min-width="144"
      ></el-table-column> -->
      <el-table-column label="状态" min-width="112">
        <template #default="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :loading="switchOpts.loading"
            :before-change="handleToggleSwitch.bind(null, scope.row, 'state')"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="192">
        <template #default="scope">
          <PipeDatetime :value="scope.row.createTime" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button-group class="ml-4">
            <el-tooltip effect="dark" content="会员详情">
              <el-button
                :icon="Document"
                @click="handleClickRowDetail(scope.row)"
              />
            </el-tooltip>
            <el-tooltip effect="dark" content="会员订单">
              <el-button
                :icon="Goods"
                @click="handleClickRowNav(scope.row, 'order_list')"
              />
            </el-tooltip>
            <el-tooltip effect="dark" content="会员充值">
              <el-button
                :icon="Coin"
                @click="handleClickRowRecharge(scope.row)"
              />
            </el-tooltip>
            <el-tooltip effect="dark" content="提现记录">
              <el-button
                :icon="Wallet"
                @click="handleClickRowNav(scope.row, 'capital_list')"
              />
            </el-tooltip>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="pageOpts.page.value"
      :page-sizes="pageOpts.sizes.value"
      :page-size="pageOpts.size.value"
      :layout="pageOpts.layout.value"
      :total="pageOpts.total.value"
      small
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </el-card>

  <DrawerDetail
    v-model="drawerOpts.visible"
    :title="drawerOpts.title"
    :size="drawerOpts.size"
    :is-edit="drawerOpts.isEdit"
    :row-data="drawerOpts.data"
    @on-refresh="requestData"
  />

  <DrawerRecharge
    v-model="drawerRecharge.visible"
    :title="drawerRecharge.title"
    :size="drawerRecharge.size"
    :is-edit="drawerRecharge.isEdit"
    :row-data="drawerRecharge.data"
    @on-refresh="requestData"
  />
</template>

<script setup lang="ts">
import { Document, Goods, Coin, Wallet } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';
import { getUsersList, updateSwitch } from '@/apis/users';
import DrawerDetail from './detail.vue';
import { ElMessage } from 'element-plus';
import { InitDrawerOpts, InitLoadOpts, InitPageOpts } from '@/utils/common';
import AsideSearch from './aside-search.vue';
import DrawerRecharge from './form-recharge.vue';

import { useRouter } from 'vue-router';
const router = useRouter();

// 加载状态
const loadOpts = reactive(InitLoadOpts());

// 查询数据（默认执行一次）
let searchData: any;
const handleClickSearch = (data: any) => {
  searchData = data;
  requestData();
};

// 列表数据
let tableData = ref<API.user.EntitySchema[]>();

// 分页数据
const pageOpts = InitPageOpts({
  page: 1,
  size: 10
});

// 抽屉
const drawerOpts = reactive(InitDrawerOpts<API.user.EntitySchema>());
const drawerRecharge = reactive(InitDrawerOpts<API.user.EntitySchema>());

// switch load status
const switchOpts = reactive({
  loading: false
});

// 切换显示条数
const handleSizeChange = (size: number) => {
  pageOpts.size.value = size;
  pageOpts.page.value = 1;
  requestData();
};

// 切换页数
const handleCurrentChange = (page: number) => {
  pageOpts.page.value = page;
  requestData();
};

// 切换状态
const handleToggleSwitch = async (
  item: API.user.EntitySchema,
  field: keyof API.user.EntitySchema
): Promise<any> => {
  switchOpts.loading = true;
  try {
    const res = await updateSwitch(item.ownId!, {
      [field]: +!item[field]
    });
    switchOpts.loading = false;
    ElMessage.success(res.message);
    return Promise.resolve(true);
  } catch (err: any) {
    switchOpts.loading = false;
    return Promise.reject(new Error('Error'));
  }
};

// 详情
const handleClickRowDetail = (row: API.user.EntitySchema) => {
  drawerOpts.title = '详情';
  drawerOpts.isEdit = true;
  drawerOpts.data = row;
  drawerOpts.visible = true;
};

// btn - 页面跳转
const handleClickRowNav = (row: API.user.EntitySchema, pageName: string) => {
  router.push({
    name: pageName,
    query: {
      // userOwnId: row.ownId
      nickname: row.nickname
    }
  });
};

// 充值
const handleClickRowRecharge = (row: API.user.EntitySchema) => {
  drawerRecharge.title = '会员充值';
  drawerRecharge.isEdit = true;
  drawerRecharge.data = row;
  drawerRecharge.visible = true;
};

// 获取分页数据
const requestData = () => {
  const dataOpt = {
    field: 'more',
    page: pageOpts.page.value,
    limit: pageOpts.size.value,

    ...searchData
  };

  // 开始加载
  loadOpts.refresh = true;

  getUsersList(dataOpt)
    .then((res) => {
      tableData.value = res.data.data || [];
      pageOpts.total.value = res.data.total;

      // 加载结束
      loadOpts.refresh = false;
    })
    .catch((err) => {
      console.log('table list error', err);
      // 加载结束
      loadOpts.refresh = false;
    });
};
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
